// Copyright 2008 Silvio Massari
//
// This file is part of SilvioMassari.Automata
//
// SilvioMassari.Automata is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SilvioMassari.Automata is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SilvioMassari.Automata.  If not, see <http://www.gnu.org/licenses/>.
				
using System;
using System.Collections.Generic;
using System.Text;

namespace SilvioMassari.Automata
{
	public class PatternString<S> : Pattern<S>
	{
		public PatternString(string pattern)
		{
			if (typeof(S) != typeof(char))
			{
				throw new ApplicationException("Invalid operation. S type must be a char!");
			}

			List<Element<S>> elements = new List<Element<S>>();

			if (pattern == null || pattern.Length == 0)
			{
				throw new ArgumentNullException("pattern");
			}

			char[] a = pattern.ToCharArray();
			int c = a.Length;
			for (int i = 0; i < c; i++)
			{
				S current = (S)Convert.ChangeType(a[i], typeof(S));
				switch (a[i])
				{
					case '\\':
						{
							if (i == c - 1)
							{
								throw new ApplicationException("Sintax error. A character is missing after last '\'.");
							}

							current = (S)Convert.ChangeType(a[++i], typeof(S));
							switch (a[i])
							{
								case '\\':
								case '&':
								case '|':
								case '*':
								case '(':
								case ')':
									{
										elements.Add(new ElementData<S>(current));
										break;
									}
								default:
									{
										throw new ApplicationException("Sintax error. Invalid chracter after '\'.");
									}
							}
							break;
						}
					case '&':
						elements.Add(new ElementOperatorAnd<S>());
						break;
					case '|':
						elements.Add(new ElementOperatorOr<S>());
						break;
					case '(':
						elements.Add(new ElementOperatorOpen<S>());
						break;
					case ')':
						elements.Add(new ElementOperatorClose<S>());
						break;
					case '*':
						elements.Add(new ElementOperatorMany<S>());
						break;
					default:
						elements.Add(new ElementData<S>(current));
						break;
				}
			}
			_pattern = elements.ToArray();
		}
	}
}
